import fs from "fs-extra";
import path from "path";
import { BaseTask } from "../../common/tasks/BastTask.js";
import { CommonEnv } from "../../common/CommonEnv.js";
import { toolchain } from "../../toolchain.js";
import { WebGLEnv } from "../WebGLEnv.js";
import { createRequire } from "module";
import { compareVersions } from "compare-versions";

export abstract class WebGLProcessJsTask extends BaseTask {
    protected async processJSFiles(output: string, runEntry: 'buildForBrowser' | 'buildForMinigame'): Promise<void> {
        const puertsRoot = toolchain.unity.getPuertsInstallRoot();
        const fileGlobbers = [
            path.join(toolchain.params.workSpacePath, CommonEnv.TsOutput, '/**/*.js'),
            path.join(puertsRoot, "/**/Resources/puerts/*.mjs"),
            path.join(toolchain.params.workSpacePath, CommonEnv.PuertsWebglRoot, "/**/Resources/**/*.mjs"),
        ];
        if (toolchain.unity.isPuertsInstalledViaLocalUPM()) {
            // 通过local upm安装puerts，commonjs模块是独立的，而旧的版本
            const puertsCommonjsRoot = toolchain.unity.getPuertsCommonjsInstallRoot();
            fileGlobbers.push(path.join(puertsCommonjsRoot, "/**/Resources/**/*.mjs"));
        }

        const require = createRequire(import.meta.url);
        const outputPath = path.join(toolchain.params.workSpacePath, output);
        let globAllJS: any;
        // 获取工具版本号
        const pkgJson = path.join(toolchain.params.workSpacePath, WebGLEnv.PuertsWebgl, 'package.json');
        const webglJsRoot = path.join(toolchain.params.workSpacePath, WebGLEnv.PuertsWebgl, 'Javascripts~');
        const { version }: { version: string } = await fs.readJSON(pkgJson);
        console.log('puerts js build version:', version);
        if (compareVersions(version, '1.1.0') >= 0) {
            await fs.copyFile(path.join(webglJsRoot, 'PuertsDLLMock/dist', WebGLEnv.PuertsRuntimeJs), path.join(outputPath, WebGLEnv.PuertsRuntimeJs));
            globAllJS = require(path.join(toolchain.params.workSpacePath, WebGLEnv.PuertsWebglJSbuild, 'Javascripts~/index.js'));
        } else {
            const tscAndWebpack = require(path.join(webglJsRoot, 'build.js'));
            tscAndWebpack(outputPath);
            globAllJS = require(path.join(webglJsRoot, 'glob-js/index.js'));
        }
        globAllJS[runEntry](fileGlobbers, outputPath);
    }
}
